package com.addTools;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

//信号量
/*
* 抢车位
* 6个车位，3个车位，等别人走了再进，限流操作
* */
public class SemaphoreTest {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                //得到车位
                try {
                    semaphore.acquire();
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println("停车"+Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //释放车位
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
